#include "clientFunc.h"

// 从文件路径分离出文件名
int cutCwd(char* str1) {
    int len = strlen(str1);
    if(len > 1 && str1[len - 1] == '/') {
        str1[len - 1] = '\0';
    }
    for(int i = len - 1; i >= 0; --i) {
        if(str1[i] == '/' || i ==  0) {
            memset(str1 + i, 0, len - i);
            break;
        }
    }
    str1[0] = '/';
    return 0;
}

// 将文件名追加到路径末尾
int concatCwd(char* path, char* fileName) {
    int len = strlen(path);
    if(path[len -1] != '/') {
        strcat(path, "/");
    }
    strcat(path, fileName);
    return 0;
}

// 处理当前的token，对cwd进行相应的出栈入栈
int cwdCtl(char* cwdStr, char* token) {
    if(strcmp(token, "..") == 0) {
        cutCwd(cwdStr);        
    }
    else if(strcmp(token, ".") != 0){
        concatCwd(cwdStr, token);
    }
    return 0;
}

// 通过传入的虚拟地址，cwd栈获得一个最终路径
int parsePath(cwd_t *pcwd, char* virtualPath, char* finalPath) {
    if(virtualPath[0] == '/') {
        strncpy(finalPath, virtualPath, strlen(virtualPath));
    }
    else {
        strncpy(finalPath, pcwd->cwdStr, strlen(pcwd->cwdStr));
        char* token;
        const char delim[] = "/";
        token = strtok(virtualPath, delim);
        if(token != NULL) {
            cwdCtl(finalPath, token);
        }
        else {
            return 0;
        }
        while((token = strtok(NULL, delim)) != NULL) {
            cwdCtl(finalPath, token);
        }

    }
    return 0;
}

// 取出cwd栈中所存的路径, pwdstr用于存储路径
int getPath(const cwd_t *pcwd, char *pwdstr) {
    strncpy(pwdstr, pcwd->cwdStr, strlen(pcwd->cwdStr));
    return 0;
}

